package code.google.com.analyticsbot;

import java.util.List;
import com.google.wave.api.AbstractRobotServlet;
import com.google.wave.api.Blip;
import com.google.wave.api.Event;
import com.google.wave.api.RobotMessageBundle;
import com.google.wave.api.Wavelet;

@SuppressWarnings("serial")
public class AnalyticsbotServlet extends AbstractRobotServlet
{
	@Override
	public void processEvents(RobotMessageBundle events)
	{
		WaveDataProvider datap = new WaveDataProvider(events);
		EventAnalyzer analyzer = new EventAnalyzer(events, datap);

		List<Event> eventsArray = events.getEvents();
		for(Event e : eventsArray)
		{
			//logEvent(e);
			analyzer.processEvent(e);
		}

		datap.close();
	}

	private void logEvent(Event e)
	{
		StringBuffer message = new StringBuffer();

		String addedParticipants = "";
		if(e.getAddedParticipants() != null)
			for(String s : e.getAddedParticipants())
				addedParticipants += s + ",";

		String removedParticipants = "";
		try
		{
			if(e.getRemovedParticipants() != null)
				for(String s : e.getRemovedParticipants())
					removedParticipants += s + ",";
		}
		catch(Exception ex)
		{
			removedParticipants = "error";
		}

		String changedVersion = "error";
		try
		{
			Long l = e.getChangedVersion();
			if(l == null)
				changedVersion = "null";
			else
				changedVersion = l.toString();
		}
		catch(Exception ex)
		{
		}

		message.append(String.format("Event: type=%s, timestamp=%d, changedVersion=%s, changedTitle=%s, modifiedBy=%s, createdBlipId=%s, removedBlipId=%s, addedPaticipants=%s, removedParticipants=%s",
			e.getType(), e.getTimestamp(), changedVersion, e.getChangedTitle(), e.getModifiedBy(), e.getCreatedBlipId(), e.getRemovedBlipId(), addedParticipants, removedParticipants));

		Blip blip = e.getBlip();

		String blipContributors = "";
		for(String s : blip.getContributors())
			blipContributors += s + ",";


		message.append(String.format("; Blip: id=%s, creator=%s, contributors=%s", blip.getBlipId(), blip.getCreator(), blipContributors));

		Wavelet wavelet = e.getWavelet();
		message.append(String.format("; Wavelet: waveid=%s, waveletid=%s", wavelet.getWaveId(), wavelet.getWaveletId()));

		log(message.toString());
	}
}
